package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.demo.dao.SysUserMapper;
import com.example.demo.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class LoginController {
    @Resource
    private SysUserMapper sysUserMapper;

    @GetMapping("/login")
    public Map doLogin(String loginName, String password){
        Map<Object, Object> map = new HashMap<>();
        if(StringUtils.isBlank(loginName) || StringUtils.isBlank(password)){
            map.put("code",0);
            map.put("msg","请输入用户名和密码");
            return map ;
        }
        LambdaQueryWrapper<SysUser> lqw = new LambdaQueryWrapper();
        lqw.eq(SysUser::getLoginName, loginName);
        lqw.eq(SysUser::getPassword, password);
        List<SysUser> sysUsers = sysUserMapper.selectList(lqw);
        if(sysUsers.size()>0){
            map.put("code",200);
            map.put("data",sysUsers.get(0).getLoginName());
            map.put("msg","成功");
        }else{
            map.put("code",0);
            map.put("msg","用户名或密码错误");
        }
        return map ;
    }

    @GetMapping("/register")
    public Map doRegister(String loginName, String password){
        Map<Object, Object> map = new HashMap<>();
        if(StringUtils.isBlank(loginName) || StringUtils.isBlank(password)){
            map.put("code",0);
            map.put("msg","请输入用户名和密码");
            return map ;
        }
        LambdaQueryWrapper<SysUser> lqw = new LambdaQueryWrapper();
        lqw.eq(SysUser::getLoginName, loginName);
        List<SysUser> sysUsers = sysUserMapper.selectList(lqw);
        if(sysUsers.size()>0){
            map.put("code",0);
            map.put("msg","用户名已存在");
            return map ;
        }
        SysUser user = new SysUser();
        user.setLoginName(loginName);
        user.setPassword(password);
        //user.setName(name);
        user.setDeleted(0);
        user.setCreateTime(new Date());
        sysUserMapper.insert(user);
        map.put("code",200);
        map.put("msg","注册成功");
        return map ;
    }
}
